const redisClient = require('../../redis_client');
const {ironWarMap} = require("../config/commonConfig");
//获取铁血战争统计结果
exports.get_blood_war_info_async = function get_blood_war_info_async(key) {
    return new Promise(async function (resolve, reject) {
        try {
            const client = redisClient.getClient();
            // 使用Promise方式获取哈希表数据
            const val = await client.HGETALL(key);

            if (!val || Object.keys(val).length === 0) {
                resolve(1);
            } else {
                const parsed = Object.values(val).map(item => JSON.parse(item));
                resolve(parsed); // 成功时返回结果
            }
        } catch (err) {
            console.error('获取铁血战争统计结果,先查询redis失败:', err.message);
            return 0;
        }
    });
};

exports.get_blood_war_info = function get_blood_war_info(key) {
    // 获取Redis客户端实例
    return new Promise(async (resolve, reject) => {
        try {
            const client = redisClient.getClient();
            const value = await client.HGETALL(key);
            console.log("value======", value);
            if (!value || Object.keys(value).length === 0) {
                resolve(1);
            } else {
                const parsed = Object.values(value).map(item => JSON.parse(item));
                resolve(parsed); // 成功时返回结果
            }
        } catch (error) {
            console.error("获取Redis值失败:", error);
            reject(error); // 失败时抛出错误
        }
    });
};

//统计铁血战争对应名单历史的人数
exports.history_hash_table = function history_hash_table(key, cb) {
    try {
        const newKey = key.replace("last_", "history_");
        const client = redisClient.getClient();
        client.RENAME(key, newKey, (err, result) => {
            if (err) {
                console.error('history_hash表失败');
                cb(-1);
            } else {
                cb(result);
            }
        });
    } catch (error) {
        console.log("统计铁血战争对应名单历史的人数", error);
    }
};

exports.get_blood_war_info_merge = function get_blood_war_info_merge(key, hisKey) {
    return new Promise(async function (resolve, reject) {
        const client = redisClient.getClient();
        try {
            const [result1, result2] = await Promise.all([
                client.HGETALL(key),
                client.HGETALL(hisKey)
            ]);
            let processedResults = [];
            console.log("结果1为:", result1);
            console.log("结果2为:", result2);
            // 处理第一个key的数据
            if (result1 && Object.keys(result1).length > 0) {
                processedResults = Object.values(result1).map(item => JSON.parse(item));
            }

            // 处理第二个key的数据
            if (result2 && Object.keys(result2).length > 0) {
                processedResults.push(...Object.values(result2).map(item => JSON.parse(item)));
            }

            if (!processedResults || processedResults.length === 0) {
                resolve(1);
            } else {
                resolve(processedResults);
            }
        } catch (error) {
            resolve(0);
            console.error('合并铁血战争统计结果,先查询redis失败:', error.message);
        }
    });
};

exports.get_robot_flag = function get_robot_flag() {
    return new Promise(async function (resolve, reject) {
            try{
                const client = redisClient.getClient();
                const  value = await client.get("robot_flag");
                if (value == null) {
                    resolve(1)
                } else {
                    resolve(value);
                }
            }catch (error) {
                console.error('获取机器人占位开关失败:', error.message);
                resolve(0);
            }
    });
};

exports.get_once_active = function get_once_active() {
    return new Promise(async function (resolve, reject) {
        try {
            const client = redisClient.getClient();
            const value = await client.HGETALL('user_once_active');
            console.log("value======", value);
            if (!value || Object.keys(value).length === 0) {
                resolve(1);
            } else {
                const parsed = Object.values(value).map(item => JSON.parse(item));
                resolve(parsed); // 成功时返回结果
            }
        } catch (error) {
            console.error("获取Redis值失败:", error);
            reject(error); // 失败时抛出错误
        }
    });
}

//铁血战争统计名单保存入库
exports.save_blood_war_info = function save_blood_war_info(type,info){
    return new Promise(async (resolve) =>{
        try{
            const client = redisClient.getClient();
            const  val = await client.HGET(type, info.userId);
            console.log(val);
            if (val != null) {
                resolve(1)
            } else {
                const count = await client.HLEN(type);
                console.log("统计铁血战争对应名单key:",type,count);
                let strArr = type.split("iron_blood_war_");
                let str = strArr[1];
                console.log("对应的等级:",str);
                if(count < ironWarMap.get(parseInt(str))){
                    console.info("打印入参:",info);
                    // 保存入库
                    client.HSET(type, info.userId, JSON.stringify(info), (err) => {
                        if (err) {
                            console.error('保存用户数据失败');
                            resolve(0);
                        }
                        console.log('数据保存成功',info);
                        resolve(info);
                    });
                } else {
                    resolve(2);
                }
            }
        }catch (error) {
            console.log("铁血战争统计名单保存入库失败", error);
        }
    });
}